<?php
namespace app\web\controller;

use app\model\Theme; 

class Order extends Base
{
    public function Order()
    {
global $_G, $_P;
if (strstr($_SERVER['HTTP_HOST'],".y.yixuan.net")!==false){
    return_msg('请不要使用管理网址操作!');
}

$system = $_G['system'];
$GLOBALS['frames'] = array();
$title = '交易';
$_G['page']['title'] = $title.'列表 - '. $system['title'];
//load_func('tpl');
$id = intval ( $_P['id'] );
$themeid = intval($_P['themeid']);
if($themeid <= 0){
	$themeid = Theme::getDefaultThemenew();
}
$theme = Theme::getThemeById($themeid);
if(empty($theme['id'])){
	return_msg('还没有创建活动,请联系管理员');
}
$config = 	Theme::getConfig($themeid);
$do = 'order';
$op = !empty($_P['op']) ? $_P['op'] : 'display';
$url = createWebUrl($do,array('op' => 'display','themeid'=>$themeid));
$paystate = empty($_P['paystate']) ? 'all':$_P['paystate'];
$pm = array(":themeid"=>$themeid);
if($op == 'display'){
    
	$themelist = Theme::getAllTheme();
    $pageNumber = max ( 1, intval ( $_P['page'] ) );
    if ($theme['endtime']<strtotime("-90 day")) {
        if ($pageNumber>1 && $_G['username']!=='benben') {
            return_msg('活动结束超3个月,无法查看');
        }
        $pageSize = 20;
    }elseif ($theme['endtime']<strtotime("-30 day")) {
        if ($pageNumber>1 && $_G['username']!=='benben' && $_G['username']!=='caiwu' && $_G['username']!=='chuna') {
            return_msg('活动结束超1个月,无法查看');
        }
        $pageSize = 20;
    }else{
		$pageSize = 50;
	}
    
 	if (empty($_P['createtime']['start'])){
		$starttime =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
		$starttime =  strtotime(date('Y-m-d 00:00:00',$starttime));
	}else{
		$starttime =  strtotime($_P['createtime']['start']);
	}
    $endtime = empty($_P['createtime']['end']) ? strtotime(date('Y-m-d 23:59:59',TIMESTAMP)): strtotime($_P['createtime']['end']);
    
    
    $condition = " and 1=1 ";
    $condition = " and ord.themeid = '{$themeid}' ";
    $condition.= " and ord.addtime > '{$starttime}' and ord.addtime <= '{$endtime}' ";
    
    
    if(!isset($_P['paystate'])){
        $paystate = -10;
    }else{
        $paystate = intval($_P['paystate']);
    }
    if($paystate >= -1){
        $condition.= " and ord.paystate = '{$paystate}'  ";
    }

	if ($_G['role'] != 'clerk'){
	    if(!isset($_P['ispay'])){
	        $ispay = -10;
	    }else{
	        $ispay = intval($_P['ispay']);
	    }
	    if($ispay == -9){
	        $condition.= " and checktime is null ";
	    }elseif($ispay == -8){
	        $condition.= " and checktime>0 ";
	    }elseif($ispay == -1){
	        $condition.= " and paystate  = 1 and ispay = -1 ";
	    }elseif($ispay == 0){
	        $condition.= " and paystate  <1 and ispay = 0 ";
	    }elseif($ispay == 1){
	        $condition.= " and paystate  =1 and ispay > -1 ";
	    }elseif($ispay == -11){
	        $condition.= " and paystate  =1 and tiaozhuan =1 ";
	    }
	}
    if(!isset($_P['type'])){
		$type = -1;
	}else{
		$type = intval($_P['type']);
	}
	if($type >= 0){
		$condition.= " and ord.ordertype = '{$type}'  ";
	}

    if(!isset($_P['status'])){
        $status = -1;
    }else{
        $status = intval($_P['status']);
    }
    if($status >= 0){
        $condition.= " and ord.status = '{$status}'  ";
    }
    
    $keyword = trim($_P['keyword']);
    if(!empty($keyword)){
        $condition.= " and (m2.nickname like '%{$keyword}%' or ord.username like '%{$keyword}%' or ord.mobile like '%{$keyword}%' or ord.ordersn like '%{$keyword}%' or ord.uniontid like '%{$keyword}%')";
    }
    
    $sql = "SELECT ord.*,m2.nickname,m2.avatar FROM " . tablename ( t_order ) . " as ord
						left join " . tablename (t_fans) . " as m2 on ord.openid = m2.openid
						WHERE 1=1  {$condition} and m2.themeid = '{$themeid}' ORDER BY ord.id desc
									LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;
   
    $list = db_select ( $sql );
    $total = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_order ) . " as ord
						left join " . tablename (t_fans) . " as m2 on ord.openid = m2.openid
					WHERE 1=1  {$condition} ORDER BY ord.id" );

	$gsumall = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
			WHERE themeid ='{$themeid}'  and paystate  = 1 and realfee > 0 " )));
	$gsum0 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
			WHERE themeid ='{$themeid}' and ordertype = 0  and paystate  = 1 " )));
	$gsum1 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
			WHERE themeid ='{$themeid}' and ordertype = 1  and paystate  = 1 " )));
	$gsum9 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
			WHERE themeid ='{$themeid}' and ordertype = 9 and paystate  = 1 " )));
	$gsum2 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
			WHERE themeid ='{$themeid}' and ordertype = 2 and paystate  = 1 " )));	
	$gsum4 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
			WHERE themeid ='{$themeid}' and ordertype = 4 and paystate  = 1 " )));	
	$gsum5 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
			WHERE themeid ='{$themeid}' and ordertype = 5 and paystate  = 1 " )));	
	$gsum6 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
			WHERE themeid ='{$themeid}' and ordertype = 6 and paystate  = 1 " )));	
	$gsum7 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
			WHERE themeid ='{$themeid}' and ordertype = 7 and paystate  = 1 " )));	

	$gsum10 = db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_order ) . "
			WHERE themeid ='{$themeid}'  " );
	$gsum11 = db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_order ) . "
			WHERE themeid ='{$themeid}'  and paystate  = 0  " );
	$gsum12 = db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_order ) . "
			WHERE themeid ='{$themeid}'  and paystate  = 1 and realfee > 0 " );
	$gsum13 = db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_order ) . "
			WHERE themeid ='{$themeid}'  and paystate  = -1 and realfee > 0 " );

	if ($_G['isSuperAdmin'] ){
		$gsum20 = db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_order ) . "
				WHERE themeid ='{$themeid}' and paystate  = 1 and tiaozhuan=0 and realfee > 0 and checktime>0" );
		$gsum24 = db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_order ) . "
				WHERE themeid ='{$themeid}' and paystate  = 1 and tiaozhuan=0 and realfee > 0 and checktime is null" );
		$gsum21 = db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_order ) . "
				WHERE themeid ='{$themeid}'  and paystate  = 1 and tiaozhuan=0 and ispay = -1 " );
		$gsum25 = db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_order ) . "
				WHERE themeid ='{$themeid}'  and paystate  = 1 and tiaozhuan=1" );
		$gsum22 = db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_order ) . "
				WHERE themeid ='{$themeid}'  and paystate  <1 and ispay = 0 " );
		$gsum23 = db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_order ) . "
				WHERE themeid ='{$themeid}'  and paystate  =1 and tiaozhuan=0 and ispay > -1 " );
	}
    $pager = pagination ( $total, $pageNumber, $pageSize );
}

if ($op == 'delete') {
    
    $order = db_find ( "SELECT * FROM " . tablename ( t_order ) . " WHERE id = '{$id}'" );
    if ($order['status'] !=0) {
        return_tips ( '当前状态不可删除' );
    }
    db_delete ( t_order, array ('id' => $id) );
    return_tips ( '删除成功！', referer (), 'success' );
}




// if($op == 'status11') {
//     $order = db_find ( "SELECT * FROM " . tablename ( t_order ) . " WHERE id = '{$orderid}'" );
//     $status = 0 ;
//     if($order['status'] == 1){
//         $status = 2;
//         if($order['ordertype'] == 'buy'){
//             db_update ( t_record, array('status'=>2), array ('id'=> $order['detailid']) );
//         }elseif ($order['ordertype'] == 'special'){
//             db_update ( t_buy, array('status'=>2), array ('id'=> $order['detailid']) );
//         }
//     }
//     db_update(t_order, array('status' => $status), array('id' => $orderid));
//     return_tips ( '变更成功！', referer (), 'success' );
// }


if($op == 'checkpay'){
	if (!$_G['isSuperAdmin'] ){
		return_tips ( '无权操作', referer (), 'error' );
	}
	$orderlist = db_select ( "SELECT * FROM " . tablename (t_order) . " WHERE id = '{$id}' " );
	if(empty($orderlist)){
		return_tips ( '没有找到定单', referer (), 'error' );
	}else{
		$okpay = 0;
		$unpay = 0;
		foreach ($orderlist as $index => $item){
		    $checkresult = checkWechatPayByOrderNo($item['tid'],$system);
			if($checkresult['errcode'] == 0 && $checkresult['fee'] ==$item['orderfee']){
			    $order = db_find ( "SELECT * FROM ".tablename(t_order)."
					WHERE  tid ='{$item['tid']}'" );
			    $record = db_find ( "SELECT * FROM " . tablename (t_record) . " WHERE  id = :id",array(":id"=>$order['masterid']));
			    if($order['paystate'] == 0 || $record['status']==0){
			        $data = array(
			            'paystate'=>1,
			            'status'  =>1,
			            'paytime'  =>TIMESTAMP,
			            'realfee'  =>$checkresult['fee'],
			        );
			        db_update(t_order,$data, array('id' => $order['id']));
			        db_update (t_record, array('status'=>1), array ('id'=> $order['masterid']) );
			        if($record['type'] == 1){
			            $p1 = $pm;
			            $p1[':pid'] = $record['pid'];
			            $count = intval(db_fetchcolumn ( "SELECT COUNT(*) FROM  " . tablename ( t_record ) . "
								WHERE themeid =:themeid and pid = :pid and type = 1 and status > 0 ",$pm));
			            if($count > $config['maxcount']){
			                db_update(t_record,array("isfinish"=>1),array("id"=>$record['pid']));
			            }
			        }
			    }
		    	$data = array(
		            'ispay'=>-1,
		            'checktime'  =>TIMESTAMP,
		        );
		        db_update(t_order,$data, array('id' => $item['id']));
				$okpay++;
			}else{
		    	$data = array(
		            'ispay'=>$checkresult['fee'],
		            'checktime'  =>TIMESTAMP,
		        );
		        db_update(t_order,$data, array('id' => $item['id']));
				$unpay++;
			}
		}
		// $theady = strtotime('-1440 minute');
		// db_query("delete from ".tablename(t_order)." WHERE paystate = 0 and addtime < '{$theady}' ");
		// db_query("delete from ".tablename(t_record)." WHERE status = 0 and addtime < '{$theady}' ");

		$result= '检查结果:异常定单:'.$unpay.'笔，正常定单:'.$okpay.'笔，请刷新当前页面查看最新定单信息!';
		return_tips ( $result, referer () );
	}
	
	
}

if($op == 'checkpaylistcz'){
	if (!$_G['isSuperAdmin'] ){
		return_tips ( '无权操作', referer (), 'error' );
	}
    db_query("UPDATE ".tablename(t_order)." SET ispay = null,checktime=null");
    return_tips ( "重置较验成功", referer () );
}

if($op == 'checkunpaylist'){
	if (!$_G['isSuperAdmin'] ){
		return_tips ( '无权操作', referer (), 'error' );
	}
	$orderlist = db_select ( "SELECT * FROM " . tablename (t_order) . " WHERE themeid = '{$themeid}' and paystate = 0 and checktime is null limit 100" );
	if(empty($orderlist)){
		return_tips ( '所有未支付定单已核验', referer (), 'error' );
	}else{
		$okpay = 0;
		$unpay = 0;
		foreach ($orderlist as $index => $item){
		    $checkresult = checkWechatPayByOrderNo($item['tid'],$system);

			if($checkresult['errcode'] == 0 && $checkresult['fee'] ==$item['orderfee']){
			  //   $order = db_find ( "SELECT * FROM ".tablename(t_order)."
					// WHERE  tid ='{$item['tid']}'" );
			  //   if($order['paystate'] == 0){
			  //       $data = array(
			  //           'paystate'=>1,
			  //           'status'  =>1,
			  //           'realfee'  =>$checkresult['fee'],
			  //       );
			  //       db_update(t_order,$data, array('id' => $order['id']));
			  //       db_update (t_record, array('status'=>1), array ('id'=> $order['masterid']) );
			  //       $record = db_find ( "SELECT * FROM " . tablename (t_record) . " WHERE  id = :id",array(":id"=>$order['masterid']));
			  //       if($record['type'] == 1){
			  //           $p1 = $pm;
			  //           $p1[':pid'] = $record['pid'];
			  //           $count = intval(db_fetchcolumn ( "SELECT COUNT(*) FROM  " . tablename ( t_record ) . "
					// 			WHERE themeid =:themeid and pid = :pid and type = 1 and status > 0 ",$pm));
			  //           if($count > $config['maxcount']){
			  //               db_update(t_record,array("isfinish"=>1),array("id"=>$record['pid']));
			  //           }
			  //       }
			  //   }
		    	$data = array(
		            'ispay'=>-1,
		            'checktime'  =>TIMESTAMP,
		        );
		        db_update(t_order,$data, array('id' => $item['id']));
				$okpay++;
			}else{
		    	$data = array(
		            'ispay'=>$checkresult['fee'],
		            'checktime'  =>TIMESTAMP,
		        );
		        db_update(t_order,$data, array('id' => $item['id']));
				$unpay++;
			}
		}
		// $theady = strtotime('-1440 minute');
		// db_query("delete from ".tablename(t_order)." WHERE paystate = 0 and addtime < '{$theady}' ");
		// db_query("delete from ".tablename(t_record)." WHERE status = 0 and addtime < '{$theady}' ");

		$result= '检查结果:异常定单:'.$unpay.'笔，正常定单:'.$okpay.'笔，请刷新当前页面查看最新定单信息!';
		return_tips ( $result, referer () );
	}
	
	
}


if($op == 'checkpaylist'){
	if (!$_G['isSuperAdmin'] ){
		return_tips ( '无权操作', referer (), 'error' );
	}
	$orderlist = db_select ( "SELECT * FROM " . tablename (t_order) . " WHERE themeid = '{$themeid}' and paystate = 1  and tiaozhuan = 0 and realfee > 0 and checktime is null limit 100" );
	if(empty($orderlist)){
		return_tips ( '所有定单已核验', referer (), 'error' );
	}else{
		$okpay = 0;
		$unpay = 0;
		foreach ($orderlist as $index => $item){
		    $checkresult = checkWechatPayByOrderNo($item['tid'],$system);

			if($checkresult['errcode'] == 0 && $checkresult['fee'] ==$item['orderfee']){
			  //   $order = db_find ( "SELECT * FROM ".tablename(t_order)."
					// WHERE  tid ='{$item['tid']}'" );
			  //   if($order['paystate'] == 0){
			  //       $data = array(
			  //           'paystate'=>1,
			  //           'status'  =>1,
			  //           'realfee'  =>$checkresult['fee'],
			  //       );
			  //       db_update(t_order,$data, array('id' => $order['id']));
			  //       db_update (t_record, array('status'=>1), array ('id'=> $order['masterid']) );
			  //       $record = db_find ( "SELECT * FROM " . tablename (t_record) . " WHERE  id = :id",array(":id"=>$order['masterid']));
			  //       if($record['type'] == 1){
			  //           $p1 = $pm;
			  //           $p1[':pid'] = $record['pid'];
			  //           $count = intval(db_fetchcolumn ( "SELECT COUNT(*) FROM  " . tablename ( t_record ) . "
					// 			WHERE themeid =:themeid and pid = :pid and type = 1 and status > 0 ",$pm));
			  //           if($count > $config['maxcount']){
			  //               db_update(t_record,array("isfinish"=>1),array("id"=>$record['pid']));
			  //           }
			  //       }
			  //   }
		    	$data = array(
		            'ispay'=>-1,
		            'checktime'  =>TIMESTAMP,
		        );
		        db_update(t_order,$data, array('id' => $item['id']));
				$okpay++;
			}else{
		    	$data = array(
		            'ispay'=>$checkresult['fee'],
		            'checktime'  =>TIMESTAMP,
		        );
		        db_update(t_order,$data, array('id' => $item['id']));
				$unpay++;
			}
		}
		// $theady = strtotime('-1440 minute');
		// db_query("delete from ".tablename(t_order)." WHERE paystate = 0 and addtime < '{$theady}' ");
		// db_query("delete from ".tablename(t_record)." WHERE status = 0 and addtime < '{$theady}' ");

		$result= '检查结果:异常定单:'.$unpay.'笔，正常定单:'.$okpay.'笔，请刷新当前页面查看最新定单信息!';
		return_tips ( $result, referer () );
	}
	
	
}




$return_clicent = get_defined_vars();
return view('/order' , $return_clicent);
}
}